﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Data;
using PokeData;

namespace PokeTD
{
    class Dashboard
    {
        private Dictionary<string, Texture2D> DashboardTextures;
        private SpriteFont font;
        private SpriteFont smallfont;
        private Texture2D background;
        private string NextWaveString;
        private Dictionary<string, Texture2D> TowerBuyTextures;
        private int page = 0;
        private Texture2D rangetexture;

        private List<BuyTableEntry> entries;
        private bool nextpagepossible = true;
        private BuyTableEntry _chosenTower;
        private DashboardState _state = DashboardState.none;

        private TowerDetail btd;
        private Waves waves;
        private Texture2D _chosenframe;
        private Player player;
        private Tower _selectedTower;

        private List<Texture2D> TypeTextures;

        private List<DashboardButton> buttons;

        public event ClickedEventArgsHandler OnPauseClicked;

        public int Page {
            get { return page; }
            set { page = value; }
        }

        public BuyTableEntry ChosenTower
        {
            get { return _chosenTower; }
            set {
                if (value == null) {
                    _chosenTower.Chosen = false;
                    _state = DashboardState.none;
                    btd = null;
                }
                _chosenTower = value;

            }
        }
        public DashboardState State {
            get { return _state; }
            set { _state = value; }
        }
        public Tower SelectedTower {
            get { return _selectedTower; }
            set { _selectedTower = value; }
        }

        public Dashboard(Dictionary<string, Texture2D> DashboardTextures, Dictionary<string, Texture2D> TowerBuyTextures, List<Texture2D> typeText, SpriteFont font, SpriteFont smallfont, Waves w, Player p, Texture2D rangetex)
        {
            buttons = new List<DashboardButton>();
            this.TowerBuyTextures = TowerBuyTextures;
            this.DashboardTextures = DashboardTextures;
            TypeTextures = typeText;
            waves = w;
            player = p;
            entries = new List<BuyTableEntry>();
            // zwei buttons: Menübutton und Nextbutton... Pausebutton kommt später.
            DashboardButton menubutton = new DashboardButton("Pause", true, new Rectangle(15, 370, 75, 20));
            menubutton.DashboardButtonClicked += new DashboardButtonEventHandler(menubutton_clicked);
            
            DashboardButton wavebutton = new DashboardButton("Weiter", true, new Rectangle(100, 370, 75, 20));
            wavebutton.DashboardButtonClicked += new DashboardButtonEventHandler(wavebutton_DashboardButtonClicked);

            DashboardButton NextPageButton = new DashboardButton(">>>", true, new Rectangle(100, 235, 75, 20));
            if (!nextpagepossible)
                NextPageButton.isActive = false;
            NextPageButton.DashboardButtonClicked += new DashboardButtonEventHandler(NextPageButton_DashboardButtonClicked);

            DashboardButton PrevPageButton = new DashboardButton("<<<", false, new Rectangle(15, 235, 75, 20));
            PrevPageButton.DashboardButtonClicked += new DashboardButtonEventHandler(PrevPageButton_DashboardButtonClicked);

            DashboardButton KaufenButton = new DashboardButton("Kaufen", true, new Rectangle(15, 665, 75, 20));
            KaufenButton.DashboardButtonClicked += new DashboardButtonEventHandler(KaufenButton_DashboardButtonClicked);

            DashboardButton UpgradeButton = new DashboardButton("Entwickeln", false, new Rectangle(15, 665, 75, 20));
            UpgradeButton.DashboardButtonClicked += new DashboardButtonEventHandler(UpgradeButton_DashboardButtonClicked);

            DashboardButton VerkaufenButton = new DashboardButton("Verkaufen", false, new Rectangle(100, 665, 75, 20));
            VerkaufenButton.DashboardButtonClicked += new DashboardButtonEventHandler(VerkaufenButton_DashboardButtonClicked);

            buttons.Add(menubutton);
            buttons.Add(wavebutton);
            buttons.Add(NextPageButton);
            buttons.Add(PrevPageButton);
            buttons.Add(KaufenButton);
            buttons.Add(UpgradeButton);
            buttons.Add(VerkaufenButton);

            this.font = font;
            this.smallfont = smallfont;
            background = DashboardTextures["dashboard"];
            _chosenframe = DashboardTextures["chosenframe"];

            rangetexture = rangetex;
            foreach (DashboardButton bttn in buttons) {
                bttn.hoverTexture = DashboardTextures["dbbHover"];
                bttn.inactiveTexture = DashboardTextures["dbbInactive"];
                bttn.normalTexture = DashboardTextures["dbbNormal"];
                bttn.pressedTexture = DashboardTextures["dbbPressed"];
                bttn.textColor = Color.White;
                bttn.Font = smallfont;
            }
            updateTowerBuyTable();
        }

        void VerkaufenButton_DashboardButtonClicked(object Sender, DashboardButtonEventArgs e)
        {
            player.RemoveTower(_selectedTower);
            waves.UpdatePaths();
            _state = DashboardState.none;
        }

        void UpgradeButton_DashboardButtonClicked(object Sender, DashboardButtonEventArgs e)
        {
            player.UpgradeTower(_selectedTower);
            //_state = DashboardState.none;
        }

        void KaufenButton_DashboardButtonClicked(object Sender, DashboardButtonEventArgs e)
        {
            _state = DashboardState.none;
        }

        void PrevPageButton_DashboardButtonClicked(object Sender, DashboardButtonEventArgs e)
        {
            DashboardButton temp = (DashboardButton)Sender;
            PreviousTowerPage();
            updateTowerBuyTable();
            if (page == 0)
            {
                temp.isActive = false;
            }
            else
            {
                temp.isActive = true;
            }
            buttons[2].isActive = true;
        }

        void NextPageButton_DashboardButtonClicked(object Sender, DashboardButtonEventArgs e)
        {
            DashboardButton temp = (DashboardButton)Sender;
            NextTowerPage();
            updateTowerBuyTable();
            if (nextpagepossible == false)
            {
                temp.isActive = false;
            }
            else
            {
                temp.isActive = true;
            }
            buttons[3].isActive = true;
        }

        void wavebutton_DashboardButtonClicked(object Sender, DashboardButtonEventArgs e)
        {
            waves.Next();
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            // Merke: Das ist nicht der ideale Platz für sowas :D
            if (_state == DashboardState.UpgradeTower)
            {
                Vector2 circlerenderroot = _selectedTower.Center + player.Map.RenderRoot - new Vector2((int)_selectedTower.Range, (int)_selectedTower.Range);
                Rectangle destrec = new Rectangle((int)circlerenderroot.X, (int)circlerenderroot.Y, (int)_selectedTower.Range * 2, (int)_selectedTower.Range * 2);
                spriteBatch.Draw(rangetexture, destrec, new Color(255, 255, 255, 50));
            }

            spriteBatch.Draw(background, new Rectangle(0, 0, 300, 700), Color.White);
            
            // Geschenke!
            spriteBatch.DrawString(font, "Leben: " + player.Lives, new Vector2(10, 260), Color.Black);
            // Nächste Welle?
            spriteBatch.DrawString(font, "Nächste Welle in: " + NextWaveString, new Vector2(10, 280), Color.Black);
            // I can has geld.
            string moneytext = "Geld: " + player.Money + " ";
            spriteBatch.DrawString(font, moneytext, new Vector2(10, 300), Color.Black);
            spriteBatch.Draw(DashboardTextures["pokedollar"], new Vector2(10 + font.MeasureString(moneytext).X, 306), Color.Black);
            if ((_state == DashboardState.BuyTower) || (_state == DashboardState.UpgradeTower))
            {
                btd.Draw(spriteBatch, DashboardTextures["pokedollar_small"]);
            }
            //Buttons... mit Spezialbehandlung.
            foreach (DashboardButton bttn in buttons)
            {
                switch (bttn.Caption)
                {
                    case "Kaufen":
                        if (_state == DashboardState.BuyTower)
                        {
                            bttn.Draw(spriteBatch);
                        }
                        break;
                    case "Entwickeln":
                        if (_state == DashboardState.UpgradeTower)
                            bttn.Draw(spriteBatch);
                        break;
                    case "Verkaufen":
                        if (_state == DashboardState.UpgradeTower)
                            bttn.Draw(spriteBatch);
                        break;
                    default: bttn.Draw(spriteBatch); break;
                }
            }
            foreach (BuyTableEntry ent in entries)
            {
                ent.Draw(spriteBatch);
            }

        }
        public void Update()
        {
            foreach (DashboardButton bttn in buttons)
            {
                switch (bttn.Caption)
                {
                    case "Kaufen":
                        if (_state == DashboardState.BuyTower)
                        {
                            if (player.Money >= btd.Cost)
                                bttn.isActive = true;
                            else
                                bttn.isActive = false;
                            bttn.Update();
                        }
                        break;
                    case "Entwickeln":
                        if (_state == DashboardState.UpgradeTower)
                        {
                            if (player.Money >= btd.UpgradeCost)
                                bttn.isActive = true;
                            else
                                bttn.isActive = false;
                            if (_selectedTower.UpgradeTo == -1)
                                bttn.isActive = false;
                            bttn.Update();
                        }
                        else
                            bttn.isActive = false;
                        break;
                    case "Verkaufen":
                        if (_state == DashboardState.UpgradeTower)
                        {
                            bttn.isActive = true;
                            bttn.Update();
                        }
                        else
                            bttn.isActive = false;
                        break;
                    default: bttn.Update(); break;
                }
            }
            foreach (BuyTableEntry ent in entries)
            {
                ent.Update();
            }
            int secs = waves.secondsToNextWave % 60;
            int min = (waves.secondsToNextWave - secs) / 60;
            NextWaveString = min.ToString() + ":";
            if (secs < 10)
                NextWaveString += "0" + secs.ToString();
            else
                NextWaveString += secs.ToString();
        }
        public void NextTowerPage()
        {
            if(nextpagepossible)
                page++;
        }
        public void PreviousTowerPage()
        {
            if(page != 0)
                page--;
        }
        private void menubutton_clicked(object sender, DashboardButtonEventArgs e)
        {
            OnPauseClicked(this, new ClickedEventArgs());
        }
        public void updateTowerBuyTable()
        {
            IEnumerable<DataRow> q = (from a in Globals.waveDS.Towers
                 where a.isbase == true
                 select a).Skip(6 * page).Take(6);
            // Immer sechs ergebnisse. Fuck Yeah.
            // Aus Platzgründen muss ein Sprite auf 92x92 px gezeichnet werden. Sollte sich aber eh ausgehen
            entries.Clear();
            int i = 0;
            foreach (WavesDS.TowersRow r in q)
            {
                BuyTableEntry temp;
                if (i < 3)
                {
                    temp = new BuyTableEntry(TowerBuyTextures["buy" + r.id.ToString()], r.Name, r.id, new Vector2(15 + i * 92, 15),smallfont,_chosenframe, r.Cost,r.Range);
                }
                else
                {
                    temp = new BuyTableEntry(TowerBuyTextures["buy" + r.id.ToString()], r.Name, r.id, new Vector2(15 + (i - 3) * 92, 125), smallfont, _chosenframe, r.Cost, r.Range);
                }
                temp.TowerBuyTableEntryClicked += new TowerBuyTableEntryEventHandler(TowerBuyTableEntryClicked);
                entries.Add(temp);
                i++;
            }
            if (i < 5)
                nextpagepossible = false;
            else
                nextpagepossible = true;

        }
        private void TowerBuyTableEntryClicked(object sender, TowerBuyTableEntryEventArgs e)
        {
            _chosenTower = (BuyTableEntry)sender;
            _state = DashboardState.BuyTower;
            foreach (BuyTableEntry ent in entries)
            {
                ent.Chosen = false;
            }
            _chosenTower.Chosen = true;
            
            btd = new TowerDetail(_chosenTower.TowerID, TowerBuyTextures, new Vector2(15, 425), new SpriteFont[] {font, smallfont}, TypeTextures, true);

        }
        public void SelectBuyTableEntry(int index) {
            if (index < entries.Count) {
                TowerBuyTableEntryClicked(entries[index], null);
            }
        }

        public void player_TowerCreated(object sender, TowerCreatedEventArgs e, Tower t)
        {
            t.Clicked += new ClickedEventArgsHandler(t_Clicked);
            if (_state == DashboardState.UpgradeTower) {
                t_Clicked(t, null);
            }
        }

        void t_Clicked(object sender, ClickedEventArgs e)
        {
            Tower t = (Tower)sender;

            _selectedTower = t;
            btd = new TowerDetail(t.TowerType, TowerBuyTextures, new Vector2(15, 425), new SpriteFont[] { font, smallfont }, TypeTextures, false);
            _state = DashboardState.UpgradeTower;
        }
    }
}
